<template>
  <div class="components-container" v-cloak>
    <sweet-modal ref="dialog" class="dialog" :sweetModalMaxWidth="pageWidth">
      <h3>{{title}}</h3>
      <div style="margin:10px 20px">
        <div class="layui-form-item">
            <div class="layui-inline">
            <label class="layui-form-label">进货人员</label>
            <div class="layui-input-inline">
              <el-input v-model="regInfo.DPIINMAN" :disabled='isINFO'></el-input> 
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">进货日期</label>
            <div class="layui-input-inline backcolor">
                <el-date-picker v-date type="date" v-model="regInfo.DPIINDATE" :disabled='isINFO'></el-date-picker>
            </div>
          </div>
          <div class="layui-inline" v-if="ishowpc">
            <label class="layui-form-label">批次</label>
            <div class="layui-input-inline">
              <el-input v-model="regInfo.DPIBATCH" disabled></el-input>
            </div>
          </div>
        </div>
      </div>
      <div :style="{maxHeight:maxHeight+'px'}" style="overflow:auto;">
        <table class="layui-table" style="border-spacing: 0;">
          <thead>
            <tr>
              <th>物品所属</th>
              <th>物品名称</th>
              <th>存放位置</th>
              <th>数量</th>
              <th v-if="isshowmoney">金额</th>
              <!-- <th>进货价格</th> -->
              <th>操作</th>
            </tr>
          </thead>
          <tbody ref='inputs'>
            <tr class="allRow" v-for="(chl,index) in chlList">
              <td>
                <!-- @keydown.enter.native="enterEvent(index,0)" -->
                <el-select @change="chaSelect($event)" ref="select" v-model="chl.DPGATTRIBUTE" clearable 
                  :filter-method="chaFilter" :disabled='isINFO' filterable>
                  <el-option v-for="item in goodsbelong" :key="item.CHAID" :label="item.CHANAME" :value="item.CHAID">
                  </el-option>
                </el-select>
              </td>
              <td>
                <el-select @visible-change="Goodname(chl,$event)" ref="selects" v-model="chl.DPLDPGID" clearable 
                  :filter-method="chaFilter" :disabled='isINFO' filterable>
                  <el-option v-for="item in chaList" :key="item.DPGID" :label="item.DPGNAME" :value="item.DPGID"></el-option>
                </el-select>
              </td>
              <td>
                <el-select ref="selecta" v-model="chl.DPLDEPOSIT" clearable
                  :filter-method="chaFilter" :disabled='isINFO' filterable>
                  <el-option v-for="item in StoragePosition" :key="item.CodeValue" :label="item.CodeName" :value="item.CodeValue">
                  </el-option>
                </el-select>
              </td>
              <td>
                <el-input @keyup.native="check(index)" @input="CalculationMoney(chl,$event)" v-model="chl.DPLNUM" :disabled='isINFO'>
                </el-input>
              </td>
              <td v-if="isshowmoney">
                <el-input v-model="chl.DPLBUYPRICE" :disabled='isINFO'>
                </el-input>
              </td>
              <td>
                <button class="layui-btn layui-btn-small layui-btn-normal" @click="remove(index)" :disabled='isINFO'>
                  <i class="layui-icon">&#xe640;</i>
                </button>
              </td>

            </tr>
          </tbody>
          <tfoot>
            <tr>
              <td v-if="!isshowmoney" colspan="4"></td>
              <td v-if="isshowmoney" colspan="5"></td>
              <td>
                <button class="layui-btn layui-btn-small layui-btn-normal" @click="insert()" :disabled='isINFO'>
                  <i class="layui-icon">&#xe654;</i>
                </button>
              </td>
            </tr>
          </tfoot>
        </table>
      </div>
      <div class="layui-form-item btnCenter sweet-btn">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submit()" :loading="this.$store.state.isloading" v-if="!(this.title === '详情')">保存</el-button>
        <el-button type="primary" @click="submissions()" :loading="this.$store.state.isloading" v-if="this.title === '入库'">提交</el-button>
      </div>
    </sweet-modal>
  </div>
</template>
<style rel="stylesheet/scss" lang="scss" scoped>
  @import "src/styles/common.scss";
  .el-button+.el-button {
    margin-left: 0;
  }

  .sweet-btn {
    margin-top: 20px;
  }

</style>

<script>
  import sweetModal from "@/components/sweetModal";
  import apiBase from "@/api/apiBase.js";
  import { formatDate, timeStringToDate } from "@/utils/date.js";
  import {
    accMul,
    Subtr,
    accAdd
  } from "@/utils/operations.js";
  import { ORDER } from "@/const/orderConst.js";

  const Warehousing = "入库";
  const changes = "修改";
  const deletes = "删除";
  const submits = "提交";
  const copy = "打印";
  const INFO = "详情";

  const MANUAL = "A";
  const AUTO = "B";

  export default {
    name: "hello",
    data() {
      return {
        pageWidth: 1200,
        maxHeight: 500,
        order: null,
        title: null,
        isINFO: false,
        DPIID: null,
        //所有收费项目
        allCharge: [],
        //物品名称
        chaList: [],
        //是否显示批次
        ishowpc: false,
        //是否显示金额
        isshowmoney: null,
        
        regInfo: {
          DPIINDATE: null, //进货日期	    
	        DPIINMAN: null, //进货人员	   
          DPIBATCH: null,//批次
        },
        //收费项目
        chlList: [],
        goodsbelong: [
          {CHANAME:'后勤',CHAID: 'B'},
        ],//物品所属
        StoragePosition: [],//存放位置
        chl: {
          CHLCHAID: "", //收费项目ID（必传）
          DPGATTRIBUTE: 'B',//物品所属
          // DPLDPGID: null,	//物品类别编号	  
          DPLDPGID: "",	//物品类别编号	  
	        DPLBATCH: null,	//批次	  
          DPLNUM: null, //数量	  
	        DPLBUYPRICE: null, //进货价格	  
	        DPLDEPOSIT: null,	//存放位置
        },
      };
    },
    methods: {
      //新增行
      insert() {
      for (let index in this.chlList) {
          let chl = this.chlList[index];
          if(this.isshowmoney){
            if (chl.DPGATTRIBUTE === null || chl.DPLDPGID === null || chl.DPLNUM === null || chl.DPLDEPOSIT === null || chl.DPLBUYPRICE === null) {
              this.$message({
                type: "error",
                message: `第${parseInt(index) + 1}行信息不能有空!`
              });
              return false;
            }
          }else{
            if (chl.DPGATTRIBUTE === null || chl.DPLDPGID === null || chl.DPLNUM === null || chl.DPLDEPOSIT === null) {
              this.$message({
                type: "error",
                message: `第${parseInt(index) + 1}行信息不能有空!`
              });
              return false;
            }
          }
          
        }
        this.chlList.push(JSON.parse(JSON.stringify(this.chl)));
        return true;
      },
      //删除行
      remove(index) {
        this.chlList.splice(index, 1);
      },
      //回车事件
      enterEvent(rowNum, colNum) {
        //获取所有行
        let rows = this.$refs.inputs.getElementsByClassName("allRow");
        //获取当前行
        let currow = rows[rowNum];
        // 获取当前行所有列
        let inputs = currow.getElementsByTagName("input");
        //强制隐藏下拉框
        if (colNum === 0) {
          let chl = this.chlList[rowNum];
          if (chl.CHLCHAID.length === 0) {
            this.$message({
              type: "error",
              message: `第${parseInt(rowNum) + 1}行收费项目不能为空!`
            });
            return;
          }
          let select = this.$refs.select;
          select[rowNum].visible = false;
        }
        //最后一列
        if (colNum === inputs.length - 1) {
          //最后一行
          if (rowNum === this.chlList.length - 1) {
            //插入空行
            if (!this.insert()) {
              return;
            }
          }
          //换行
          this.$nextTick(function () {
            this.enterEvent(rowNum + 1, -1);
          });
        } else {
          //获取下一个焦点
          this.$nextTick(function () {
            inputs[colNum + 1].select();
          });
        }
      },
      //入库时候的提交
      submissions(){
        this.$confirm("确认是否提交该数据?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(callback => {
              let chlList = JSON.parse(JSON.stringify(this.chlList));
              let data = JSON.parse(JSON.stringify(this.regInfo));
              if(this.regInfo.DPIINDATE){
                data.DPIINDATE =  formatDate(this.regInfo.DPIINDATE, "yyyyMMdd");
              };
              if (chlList.length > 0) {
                data.list_Dpl = chlList;
              }
              apiBase.DoService(data, apiBase.getApiAdress().Depot.CreateAshDpi, res => {
                this.$message({
                  type: "success",
                  message: "入库成功!"
                });
                this.DPIID = res.data.content.DPIID;
                this.submission();//提交
                this.closeDialog();
                this.refreshData();
              });
            })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
      });



       
        this.$refs.dialog.close();
      },
       //入库提交
      submission(){
        let data = {
          DPIID: this.DPIID
        }
        apiBase.DoService(
          data,
          apiBase.getApiAdress().Depot.SubmitAshDpi,
          res => {
            this.$message({
              type: "success",
              message: "提交成功!"
            });
            this.refreshData();
          }
        )
      },
      initSelectData(){
        this.gettypenumber();
      },
      //打开弹出框
      open(order, id) {
        this.order = order;
        this.DPIID = id;
        this.initSelectData();
        switch (this.order) {
          case Warehousing:
            this.title = "入库";
            this.chl.DPLDEPOSIT = this.StoragePosition[0].CodeValue;
            this.isINFO = false;
            this.chlList = [];
            Object.assign(this.$data.regInfo, this.$options.data().regInfo);
            this.ishowpc = false;
            this.insert();
            this.$refs.dialog.open();
            break;
          case changes:
            this.title = "修改";
            this.chlList = [];
            Object.assign(this.$data.regInfo, this.$options.data().regInfo);
            this.isINFO = false;
            this.dataInfo(id);
            this.GetIsShowDepotbatch();//控制是否显示批次
            this.$refs.dialog.open();
            break;
          case INFO:
            this.title = "详情";
            this.isINFO = true;
            this.chlList = [];
            Object.assign(this.$data.regInfo, this.$options.data().regInfo);
            this.dataInfo(id);
            this.GetIsShowDepotbatch();//控制是否显示批次
            this.$refs.dialog.open();
          default:
        }
      },
      //选择收费项目
      chaSelect(index) {
        this.chl.DPGATTRIBUTE = index;
        this.gettypenumber();
      },
      //根据物品所属显示商品名
      Goodname(val,show){
        if(show === false) return;
        this.chaList = [];
        let data = {
        //   DPGATTRIBUTE: val.DPGATTRIBUTE
          DPGATTRIBUTE: null
        };
        apiBase.DoService(
          data,
          apiBase.getApiAdress().Depot.QueryAllAshDpg,
          res => {
            this.allCharge = res.data.content;
            this.chaList = res.data.content
          }
        )
      },
      //获取仓库存放位置
      getwarehouseadress(){
        let data = {};
        apiBase.DoService(
          data,
          apiBase.getApiAdress().Code.GetDepot,
          res => {
            this.StoragePosition = res.data.content;
          }
        )
      },
      //获取物品类别编号
      gettypenumber(){
        let data = {
          // DPGATTRIBUTE: this.chl.DPGATTRIBUTE
          DPGATTRIBUTE: null
        };
        apiBase.DoService(
          data,
          apiBase.getApiAdress().Depot.QueryAllAshDpg,  
          res => {
            this.chaList = res.data.content
          }
        )
      },
     
      //出库详情
      dataInfo(id) {
        let data = {
          DPIID: id
        };
        apiBase.DoService(data, apiBase.getApiAdress().Depot.DetailAshDpi, res => {
          this.chdData = res.data.content;
          this.regInfo.DPIINMAN = this.chdData.DPIINMAN;
          this.regInfo.DPIINDATE = this.chdData.DPIINDATEDESC;
          this.regInfo.DPIBATCH = this.chdData.DPIBATCH;
          this.chlList = this.chdData.List_Dpl;
          for(var i = 0;i < this.chlList.length;i++){
            this.chlList[i].chaList = [];
          }
        
        });
      },
    
      //ID获取收费项目
      getChaByID(chaId) {
        for (var i in this.allCharge) {
          var cha = this.allCharge[i];
          if (cha.CHAID === chaId) {
            return cha;
          }
        }
      },
      
      check(index) {
        let chl = this.chlList[index];
        chl.DPLNUM = this.checkNumber(chl.DPLNUM.toString());
      },
      isCommon() {
        return this.order === ORDER.CHEMODIFY;
      },
      //只能输入正整数
      checkNumber(value) {
        value = value.replace(/\D/g, "").replace(/^0+(?=\d)/, "");
        if (value !== "") {
          if (value.substr(0, 1) === "0" && value.length === 2) {
            value = value.substr(1, value.length);
          }
        } else {
          value = 0;
        }
        return value;
      },
      //只能输入金额
      checkMoney(value) {
        //修复第一个字符是小数点 的情况.
        if (value !== "" && value.substr(0, 1) === ".") {
          value = "";
        }
        value = value.replace(/^0*(0\.|[1-9])/, "$1"); //解决 粘贴不生效
        value = value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
        value = value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
        value = value
          .replace(".", "$#$")
          .replace(/\./g, "")
          .replace("$#$", ".");
        value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数
        if (value.indexOf(".") < 0 && value !== "") {
          //以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
          if (value.substr(0, 1) === "0" && value.length === 2) {
            value = value.substr(1, value.length);
          }
        } else if (value === "") {
          value = 0;
        }
        return value;
      },
      //计算当前行CHL
      chlCompute(index) {
        let chl = this.chlList[index];
        let cha = this.getChaByID(chl.CHLCHAID);
        if (cha) {
          chl.CHLMOUNT = chl.CHLMONEY * chl.CHLNUM;
          chl.CHLREDUCTION = cha.CHAJMMONEY * chl.CHLNUM;
          chl.CHLRECEIVED = chl.CHLMOUNT - chl.CHLREDUCTION - chl.CHLDISCOUNT;
        }
      },
      //自定义筛选
      chaFilter(val) {
        this.chaList = JSON.parse(JSON.stringify(this.allCharge));
        if (val) {
          if (val.length > 0)
            this.chaList = this.allCharge.filter(item => {
              return (
                item.DPGNAME.indexOf(val) > -1 ||
                item.DPGCODE.toLowerCase().indexOf(val.toLowerCase()) > -1
              );
            });
        }
      },
      // 计算金额
      CalculationMoney(val,num){
        if(this.isshowmoney){
          for(var i = 0;i < this.chaList.length;i++){
            if(this.chaList[i].DPGID === val.DPLDPGID){
              val.DPLBUYPRICE = this.chaList[i].DPGCOST * Number(num);
            }
          }
        }
      },
      //提交
      submit(checkout = false) {
        this.$store.state.isloading = true;
        switch (this.order) {
          case Warehousing://入库
            this.dataAdd(checkout);
            break;
          case changes://修改
            this.changesrk(checkout);
            break;
          default:
            break;
        }
      },
      //入库新增
      dataAdd(){
        let chlList = JSON.parse(JSON.stringify(this.chlList));
        let data = JSON.parse(JSON.stringify(this.regInfo));
        if(this.regInfo.DPIINDATE){
          data.DPIINDATE =  formatDate(this.regInfo.DPIINDATE, "yyyyMMdd");
        };
        if (chlList.length > 0) {
          data.list_Dpl = chlList;
        }
        apiBase.DoService(data, apiBase.getApiAdress().Depot.CreateAshDpi, res => {
          this.$message({
            type: "success",
            message: "入库成功!"
          });
          this.DPIID = res.data.content.DPIID;
          this.closeDialog();
          this.refreshData();
        });
      },
       //入库修改
      changesrk(){
        let chlList = JSON.parse(JSON.stringify(this.chlList));
        let data = JSON.parse(JSON.stringify(this.regInfo));
        if(this.regInfo.DPIINDATE){
          data.DPIINDATE =  formatDate(this.regInfo.DPIINDATE, "yyyyMMdd");
        };
        if (chlList.length > 0) {
          data.list_Dpl = chlList;
        }
        data.DPIID =  this.DPIID,
        apiBase.DoService(data, apiBase.getApiAdress().Depot.ModifyAshDpi, res => {
          this.$message({
            type: "success",
            message: "修改成功!"
          });
          this.closeDialog();
          this.refreshData();
        });
      },
      closeDialog() {
        switch (this.order) {
          case Warehousing:
            this.$refs.dialog.close();
            break;
          case INFO:
            this.$refs.dialog.close();
            break;
          case changes:
            this.$refs.dialog.close();
            break;
          default:
            break;
        }
      },
      //个性化背景颜色
      kzbackground(){
        apiBase.DoService(
          {},
          apiBase.getApiAdress().Param.GetBackgroundColor,
          res => {
            let backcolor = '';
            if(res.data.content === '20'){
              const inputs = document.querySelectorAll('.backcolor input.el-input__inner');
              backcolor = 'rgb(255,255,153)'
              for(var i = 0; i< inputs.length; i++){
              inputs[i].style.backgroundColor = backcolor
              }
            }
          }
        );
      },
      //个性化是否显示批次（仓库）
      GetIsShowDepotbatch(){
        apiBase.DoService(
          {},
          apiBase.getApiAdress().Param.GetIsShowDepotbatch,
          res => {
            this.ishowpc = res.data.content;
          }
        )
      },
      //个性化显示存放位置(仓库)
      GetIsMoreDepot(){
        apiBase.DoService(
          {},
          apiBase.getApiAdress().Param.GetIsMoreDepot,
          res => {
            console.log(res);
          }
        )
      },
      refreshData() {
        this.$emit("refreshData");
      },
    },
    created() {
      this.getwarehouseadress();
      let data = {};
      apiBase.DoService(data, apiBase.getApiAdress().Param.GetDepotisPrice, res => {
         this.isshowmoney = res.data.content;
      });
    },
    //计算属性
    computed: {
     
    },
    
    watch: {
      
    },
    mounted() {
      //个性化输入框背景颜色(火化登记)
      this.kzbackground();
      //个性化显示存放位置(仓库)
      this.GetIsMoreDepot();
    },
    components: {
      sweetModal
    }
  };

</script>
